<script setup lang="ts">
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Account"
});
import { ref, reactive } from "vue";
import { Calendar, Search } from "@element-plus/icons-vue";
import { itemList, addItem, delItem } from "@/api/admin";
// import { type DataInfo, setToken, removeToken } from "@/utils/auth";
import { json } from "stream/consumers";
import { func } from "vue-types";
// import { addDialog } from "@/components/ReDialog";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { ElNotification } from "element-plus";

import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

// 获取表格复选框id
const multipleTableRef = ref();
// 账户列表请求
const tableData = ref([]);
renders();
function renders() {
  new Promise((resolve, reject) => {
    itemList()
      .then(data => {
        resolve(data);
        console.log(JSON.parse(data));
        tableData.value = JSON.parse(data).data;
        console.log(tableData.value);
        dostatus(tableData.value);
        tableDatalen.value = tableData.value.length;
      })
      .catch(error => {
        reject(error);
      });
  });
}
function dostatus(datas) {
  for (let item of datas) {
    if (item.status == 1) {
      item.status = true;
    } else if (item.status == 2) {
      item.status = false;
    }
  }
  console.log(datas);
}

const opstatus = ref(0);
function clearVal() {
  form.account = "";
  form.type = "";
  form.password = "";
  form.passwords = "";
  form.img = "";
  form.status = true;
  form.longtime = null;
  form.shottime = null;
  form.student = null;
}
let chongzhi = () => {
  clearVal();
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 800);
  renders();
  mneuName.value = "";
};
// 账户选项
const mneuName = ref("");

const form = reactive({
  account: "", //账户名称
  type: "", //角色类型
  password: "", //密码
  passwords: "", //确认密码
  img: "", //头像
  status: true, //（1 正常，2 停用）
  longtime: 0, //管理费-长期
  shottime: 0, //管理费-短期
  student: 0 //管理费-学员
});

const status = ref();
const options = [
  {
    status: "2",
    label: "劳务公司"
  },
  {
    status: "4",
    label: "薪资审核员"
  }
];

let addon = () => {
  clearVal();
  opstatus.value = 1;
  dialogFormVisible.value = true;
  console.log(opstatus.value);
};
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const modelTitle = ref("新增账户");
// 表单校验

const ruleFormRef = ref(null);
// 初次输入密码验证
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (value.length < 6) {
    callback(new Error("密码长度应不低于6个字符"));
  } else {
    callback();
  }
};
//确认密码的验证
const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value.length < 6) {
    callback(new Error("密码长度应不低于6个字符"));
  } else if (value !== form.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
};
// 角色类型选择
const rolerules = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请选择角色类型"));
  } else {
    callback();
  }
};

const rules = ref({
  account: [{ required: true, message: "请完善账户名称", trigger: "change" }],
  roles: [{ required: true, validator: rolerules, trigger: "blur" }],
  password: [{ required: true, validator: validatePass, trigger: "blur" }],
  passwords: [{ required: true, validator: validatePass2, trigger: "blur" }],
  img: [{ required: true, message: "请选择头像", trigger: "blur" }],
  status: [{ required: true, message: "请选择", trigger: "blur" }]
});

// 账户添加
let addMneu = () => {
  console.log(ruleFormRef.value);
  console.log(form);
  console.log(form.status == true ? "1" : "2");

  ruleFormRef.value.validate(valid => {
    console.log(valid);
    // 不通过校验
    if (!valid) return ElMessage.error("请将内容填写完成后 再进行添加操作!");
    if (opstatus.value == 1) {
      let addobj = {
        account: form.account,
        type: form.type,
        roleid: form.type,
        password: form.password,
        img: form.img.replace("http://test_labour.xingyuncm.cn", ""),
        pid: 0,
        status: form.status
      };

      addItem(addobj)
        .then(data => {
          console.log(JSON.parse(data));
          if (JSON.parse(data).code == 1) {
            renders();
            dialogFormVisible.value = false;
            ElNotification({
              title: "Success",
              message: "添加成功",
              type: "success"
            });
            loading.value = true;
            setTimeout(() => {
              loading.value = false;
            }, 800);
          } else {
            ElNotification({
              title: "Error",
              message: "操作失败",
              type: "error"
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
      console.log(addobj);
    } else {
      console.log(efitid.value);
      let editobj = {};
      if (form.password == "") {
        editobj = {
          id: efitid.value,
          account: form.account,
          type:
            form.type == "劳务公司"
              ? 2
              : form.type == "薪资审核员"
                ? 4
                : form.type == "超级管理员"
                  ? 1
                  : 3,
          roleid:
            form.type == "劳务公司"
              ? 2
              : form.type == "薪资审核员"
                ? 4
                : form.type == "超级管理员"
                  ? 1
                  : 3,
          img: form.img.replace("http://test_labour.xingyuncm.cn", ""),
          pid: 0,
          status: form.status == true ? 1 : 2
        };
      } else {
        editobj = {
          id: efitid.value,
          account: form.account,
          type:
            form.type == "劳务公司"
              ? 2
              : form.type == "薪资审核员"
                ? 4
                : form.type == "超级管理员"
                  ? 1
                  : 3,
          roleid:
            form.type == "劳务公司"
              ? 2
              : form.type == "薪资审核员"
                ? 4
                : form.type == "超级管理员"
                  ? 1
                  : 3,
          password: form.password,
          img: form.img.replace("http://test_labour.xingyuncm.cn", ""),
          pid: 0,
          status: form.status == true ? 1 : 2
        };
      }
      addItem(editobj)
        .then(data => {
          console.log(JSON.parse(data));
          if (JSON.parse(data).code == 1) {
            renders();
            dialogFormVisible.value = false;
            ElNotification({
              title: "Success",
              message: "操作成功",
              type: "success"
            });
            loading.value = true;
            setTimeout(() => {
              loading.value = false;
            }, 800);
          } else {
            ElNotification({
              title: "Error",
              message: "操作失败",
              type: "error"
            });
          }
        })
        .catch(error => {
          console.log(error);
        });
      console.log(editobj);
    }
  });
};

// 加载效果
const loading = ref(false);

// 删除按钮
const delid = ref();
const centerDialogVisible = ref(false);
let delsure = elid => {
  centerDialogVisible.value = true;
  console.log(elid);
  delid.value = elid;
};

// 确认删除
let delyes = () => {
  centerDialogVisible.value = false;
  delItem({ id: delid.value })
    .then(data => {
      console.log(JSON.parse(data));
      if (JSON.parse(data).code == 1) {
        renders();
        ElNotification({
          title: "Success",
          message: "操作成功",
          type: "success"
        });
        loading.value = true;
        setTimeout(() => {
          loading.value = false;
        }, 800);
      } else {
        ElNotification({
          title: "Error",
          message: "操作失败",
          type: "error"
        });
      }
    })
    .catch(error => {
      console.log(error);
    });
};
let searchinp = () => {
  let datas = tableData.value;
  tableData.value = datas.filter(function (item) {
    if (String(item.account).indexOf(String(mneuName.value)) > -1) {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      return item;
    } else {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      tableData.value = [];
    }
  });
};

// 图片上传
//信息的收集

//图片上传成功的钩子
// 上传成功，获取返回的图片地址

let handleAvatarSuccess = res => {
  console.log(res);
  form.img = "http://test_labour.xingyuncm.cn" + res.url;
};
// 编辑
function showinfo(data) {
  for (let item of data) {
    if (item.id == efitid.value) {
      form.account = item.account;
      form.type = item.name;
      form.img = item.imgs;
      form.status = item.status == 1 ? true : false;
      form.longtime = item.manage_p;
      form.shottime = item.manage_l;
      form.student = item.manage_x;
    }
  }
}

const efitid = ref();
let editbox = edid => {
  clearVal();
  dialogFormVisible.value = true;
  efitid.value = edid;
  console.log(efitid.value);
  opstatus.value = 2;
  showinfo(tableData.value);
  console.log(opstatus.value);
};

const currentPage = ref<any>(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const tableDatalen = ref();

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};
// 点击状态切换
let switchbtn = (edids, statu) => {
  console.log(edids);
  console.log(statu);
  let yuandata = <any>{};
  for (let item of tableData.value) {
    if (item.id == edids) {
      yuandata = item;
    }
  }
  console.log(yuandata);

  let edirobj = {
    id: edids,
    account: yuandata.account,
    type: yuandata.type,
    roleid: yuandata.type,
    img: yuandata.img,
    pid: 0,
    status: statu == true ? 1 : 2
  };
  console.log(edirobj);
  
  addItem(edirobj)
    .then(data => {
      console.log(JSON.parse(data));
      if (JSON.parse(data).code == 1) {
        renders();
        dialogFormVisible.value = false;
        ElNotification({
          title: "Success",
          message: "操作成功",
          type: "success"
        });
        loading.value = true;
        setTimeout(() => {
          loading.value = false;
        }, 800);
      } else {
        ElNotification({
          title: "Error",
          message: "操作失败",
          type: "error"
        });
      }
    })
    .catch(error => {
      console.log(error);
    });
};
</script>

<template>
  <div class="pagebg">
    <h1>账户管理</h1>
    <!-- 输入框 -->
    <div class="searchbox">
      <div>
        <el-input
          style="width: 240px; margin-right: 20px"
          v-model="mneuName"
          placeholder="请输入账户名称"
          :suffix-icon="Search"
          @input="searchinp"
        />
        <el-button @click="chongzhi">重置</el-button>
      </div>
      <!-- 新增按钮 -->
      <div>
        <el-button type="primary" @click="addon">新增</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div>
      <Suspense>
        <el-table
          :data="
            tableData.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          ref="multipleTableRef"
          stripe
          row-key="id"
          border
          style="width: 100%"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
          v-loading="loading"
        >
          <el-table-column prop="id" label="序号" width="70" />
          <el-table-column prop="account" label="账户名称" width="180" />
          <el-table-column label="账户头像">
            <template v-slot="scope">
              <el-image
                style="width: 40px; height: 40px"
                :src="scope.row.imgs"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[scope.row.imgs]"
                :initial-index="4"
                fit="cover"
                :preview-teleported="true"
              />
            </template>
          </el-table-column>
          <el-table-column prop="type" label="账户角色">
            <template v-slot="scope">
              <el-tag class="mx-1" size="large">{{
                scope.row.type == 1
                  ? "超管"
                  : scope.row.type == 2
                    ? "劳务公司"
                    : scope.row.type == 3
                      ? "项目部"
                      : "审核员"
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="角色名称" />
          <el-table-column label="状态">
            <template v-slot="scope">
              <el-switch
                v-model="scope.row.status"
                width="60"
                size="large"
                inline-prompt
                active-text="开启"
                inactive-text="关闭"
                @click="switchbtn(scope.row.id, scope.row.status)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="create_time" label="创建时间" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="primary" @click="editbox(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                @click="delsure(scope.row.id)"
                v-show="scope.row.name == '超级管理员' ? false : true"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </Suspense>
      <div class="pageBox">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableDatalen"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加、编辑 弹窗 -->

    <el-dialog
      v-model="dialogFormVisible"
      :title="modelTitle"
      style="width: 60%"
    >
      <el-form :model="form" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="账户名称"
          :label-width="formLabelWidth"
          prop="account"
        >
          <el-input
            v-model="form.account"
            autocomplete="off"
            placeholder="请选择账户名称"
          />
        </el-form-item>
        <el-form-item
          label="角色类型"
          :label-width="formLabelWidth"
          prop="roles"
          v-model="form.type"
        >
          <el-select
            v-model="form.type"
            clearable
            placeholder="请选择角色类型"
            style="width: 100%"
            :disabled="opstatus == 1 ? false : true"
          >
            <el-option
              v-for="(item, index) in options"
              :key="index"
              :label="item.label"
              :value="item.status"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="账户密码"
          :label-width="formLabelWidth"
          :prop="opstatus == 1 ? 'password' : ''"
          v-show="opstatus == 1 ? true : false"
        >
          <el-input
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入账户密码"
          />
        </el-form-item>
        <el-form-item
          label="账户密码"
          :label-width="formLabelWidth"
          v-show="opstatus == 1 ? false : true"
        >
          <el-input
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入账户密码"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          :label-width="formLabelWidth"
          :prop="opstatus == 1 ? 'passwords' : ''"
          v-show="opstatus == 1 ? true : false"
        >
          <el-input
            v-model="form.passwords"
            autocomplete="off"
            placeholder="请确认密码"
          />
        </el-form-item>
        <el-form-item label="账户头像" style="margin-left: 64px" prop="img">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            action="http://test_labour.xingyuncm.cn/api/common/upload"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <div class="editmsg" v-show="opstatus == 1 ? false : true">
          <el-form-item label="管理费-长期" style="width: 30%">
            <el-input
              type="number"
              v-model="form.longtime"
              placeholder="请输入费用"
            />
          </el-form-item>
          <el-form-item label="管理费-短期" style="width: 30%">
            <el-input
              type="number"
              v-model="form.shottime"
              placeholder="请输入费用"
            />
          </el-form-item>
          <el-form-item label="管理费-学员" style="width: 30%">
            <el-input
              type="number"
              v-model="form.student"
              placeholder="请输入费用"
            />
          </el-form-item>
        </div>

        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-switch
            v-model="form.status"
            inline-prompt
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addMneu"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="Warning" width="30%" center>
      <span> 确定删除 </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="delyes"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.grow {
  padding: 0;
}
.pagebg {
  width: auto;
  height: 100%;
  background-color: #ffffff;
}
.searchbox {
  width: auto;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar {
  width: 177px;
  height: 177px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.pageBox {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.editmsg {
  margin-left: 50px;
  display: flex;
  justify-content: space-around;
}
</style>
